//
//  BrokerQueryVc.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/6/12.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "BrokerQueryVc.h"
#import "BdTV.h"
#import "NodataCell.h"
#import "BrokerDM.h"
#import "BdTV.h"
#import "config.h"
#import "SearchView.h"
#import "MJRefresh.h"
#import "UserModal.h"
#import "StringTool.h"
#import "BrokerCell.h"
#import "CommissionSubVc.h"

#import "HideTextVeiw.h"
#import "MBProgressHUD+MJ.h"


@interface BrokerQueryVc ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,SearchViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *seachEt;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *dataArray,*seachDataArray;
@property (strong, nonatomic) NodataCell *nodataCell;
@property (strong, nonatomic) BrokerDM *dataMange;
@property (strong, nonatomic) SearchView *seachView;
@property (copy, nonatomic) NSString *keyword;

@property(nonatomic,assign) Boolean isSearchType;

@property (weak, nonatomic) IBOutlet HideTextVeiw *searchTv;
@property (weak, nonatomic) IBOutlet UIButton *cacelBtn;

@property (nonatomic,assign)NSInteger pageIndex;//非搜索情况的页码
@property (nonatomic,assign)NSInteger searchIndex;//搜索情况下的页码

@end



@implementation BrokerQueryVc
@synthesize dataArray,seachEt,dataMange,seachView,nodataCell,keyword,seachDataArray,isSearchType;




- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self initView];
    
    [self refreshData];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.searchTv resignFirstResponder ];
}
-(void)initView{
    [super initView];
    
    [self.searchTv setHideText:@"可通过经纪人的姓名搜索"];
    self.cacelBtn.enabled = NO;
    [self.cacelBtn setTitle:@"" forState:UIControlStateNormal];
    
    dataMange = [[BrokerDM alloc]init];
    
    
    BdTV *titleView = [BdTV creatInstanceWithTitle:@"经纪人查询"];
    
    
    [[titleView backBtn]addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [[titleView backBtn]setTag:11];
    [[titleView doneBtn]removeFromSuperview];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:titleView];
    
    
    
    [self.seachEt setLeftViewMode:UITextFieldViewModeAlways];
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 38, 44)];
    
    UIImageView *leftView = [[UIImageView alloc]initWithFrame:CGRectMake(backView.frame.size.width/2-8, backView.frame.size.height/2-8, 15, 15)];
    [leftView setImage:[UIImage imageNamed:@"search_icom"]];
    [backView addSubview:leftView];
    [self.seachEt setLeftView:backView];
    self.seachEt.delegate = self;


    
    
    if (isIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    if (isIOS7) {
        if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
            [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        }
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    

    UIView *hd = [[UIView alloc]initWithFrame:CGRectMake(0, 0, PMW, 10)];
    [hd setBackgroundColor:UIColorFromRGB(0xF3F3F3)];
    [self.tableView setTableHeaderView:hd];
    

    seachView = [[SearchView alloc]initWithParentView:self.tableView withEt:self.seachEt];
    seachView.delegate = self;
    seachView.textView = self.searchTv;
    [seachView.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(searchLoadMore)];
    
    
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
}

#pragma mark 搜索情况下刷新数据
-(void)searchRefreshData
{
    self.searchIndex = 1;
    [self.seachView.tableView.footer resetNoMoreData];
    __weak typeof(self) bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
        
        ResulteMod *resultMod =[dataMange refreshDataWithStoreCode:@"" withKeyWord:self.keyword];
    
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (resultMod.resltState==ResultNetError) {
                
                [MBProgressHUD showError:@"网络错误"];
                
            }else if (resultMod.resltState==ResultFail){
                
                 [MBProgressHUD showError:resultMod.resultTip];;
                
            }else{
                
                    bself.seachDataArray = [[ NSMutableArray alloc]initWithArray:resultMod.dataMod];
                if (bself.seachDataArray != nil && bself.seachDataArray.count != 0) {
                    self.searchIndex ++;
                }
                   [self.seachView.tableView reloadData];
                   [self.seachView tableViewReloadAndUpFrame];
            }
            
            
        });
    });

}
#pragma mark 非搜索情况下的刷新数据
-(void)refreshData{
    
    self.pageIndex = 1;
    [nodataCell setState:nodataCellStateLoading];
    
    [self.tableView.footer resetNoMoreData];
    __weak typeof(self) bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *agencyCode = [UserModal shareUserModel].userCode;
        
              ResulteMod *resultMod  = [dataMange refreshDataWithAgencyCode2:agencyCode withKeyWord:@"*"];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
             [bself.tableView.header endRefreshing];
            
            if (resultMod.resltState==ResultNetError) {
                
                [bself.nodataCell setState:nodataCellStateNetError];
                
            }else if (resultMod.resltState==ResultFail){
                
                [bself.nodataCell setCodeErrorTip:resultMod.resultCode];
                
            }else{
                
                    bself.dataArray = [[ NSMutableArray alloc]initWithArray:resultMod.dataMod];
                    if (bself.dataArray.count == 0 || bself.dataArray == nil ) {
                        [bself.nodataCell setState:nodataCellStateNodata];
                    }
                 bself.pageIndex = (bself.dataArray.count == 0 || bself.dataArray == nil)?1:2;
            }
             [bself.tableView reloadData];
            
        });
    });
    
}

#pragma mark 搜索情况下加载更多
-(void)searchLoadMore
{
    __weak typeof(self) bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        ResulteMod *resultMod  = [dataMange loadMoreDataWithKeyword:self.keyword withIndex:bself.searchIndex];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [bself.seachView.tableView.footer endRefreshing];
            
            if (resultMod.resltState==ResultNetError) {
                
                [MBProgressHUD showError:@"网络错误"];
                
            }else if (resultMod.resltState==ResultFail){
                
                [MBProgressHUD showError:resultMod.resultTip];
                
            }else{
                
                NSMutableArray *arr = [NSMutableArray arrayWithArray:resultMod.dataMod];
                if (arr.count == 0 || arr == nil) {
                    [bself.seachView.tableView.footer noticeNoMoreData];
                }else
                {
                    bself.searchIndex ++;
                }
                [arr addObjectsFromArray:bself.seachDataArray];
                bself.seachDataArray = [[NSArray alloc]initWithArray:arr];
                [seachView tableViewReloadAndUpFrame];
                [bself.seachView.tableView reloadData];
            }
            
        });
    });
    
}


#pragma mark 非搜索情况下加载更多
-(void)loadMore
{
    
    [self.tableView reloadData];
    
    [self.tableView.footer resetNoMoreData];
    [nodataCell setState:nodataCellStateLoading];
    __weak typeof(self) bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        ResulteMod *resultMod  = [dataMange loadMoreDataWithKeyword:@"*" withIndex:bself.pageIndex];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [bself.tableView.footer endRefreshing];
            
            if (resultMod.resltState==ResultNetError) {
                
                [bself.nodataCell setState:nodataCellStateNetError];
                
            }else if (resultMod.resltState==ResultFail){
                
                [bself.nodataCell setCodeErrorTip:resultMod.resultCode];
                
            }else{
                
                NSArray *dataArr = [NSArray arrayWithArray:resultMod.dataMod];
                
                NSMutableArray *array = [[NSMutableArray alloc]initWithArray:bself.dataArray];
                [array addObjectsFromArray:dataArr];
                
                bself.dataArray = [NSArray arrayWithArray:array];
                
                
                if (dataArr.count == 0)
                {
                    [bself.tableView.footer noticeNoMoreData];
                }else
                {
                    bself.pageIndex ++;
                }
                
            }
            
            [bself.tableView reloadData];
            
            
        });
    });
    
}


-(void)btnOnclick:(UIButton*)sender{
    
    if (sender.tag==11) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }else if(sender==nodataCell.refreshBtn){
        
        [self refreshData];
    }
}





#pragma mark tableView delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (dataArray.count==0) {
        return tableView.frame.size.height;
    }
    
    return  [BrokerCell getHight:nil withTableView:tableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (dataArray.count==0) {
        [tableView setScrollEnabled:false];
        return 1;
    }
    
    [tableView setScrollEnabled:YES];
    return dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (dataArray.count==0) {
        if(!nodataCell){
            nodataCell = [[NodataCell alloc] initWithFrame:tableView.frame];
            [nodataCell setState:nodataCellStateLoading];
            [[nodataCell refreshBtn]setTag:56];
            [nodataCell.refreshBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
        }
        return nodataCell;
    }
    
    
    
    static NSString *ID = @"BrokerCell";
    BrokerCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil)
    {
        cell = [[BrokerCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        
        [cell.contentMoveView addTarget:self action:@selector(cellOnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [cell initWithTableView:self.tableView];
        
        [cell beQueryStyleCell];

    }
    
    BorkerCellModel *data = [dataArray objectAtIndex:indexPath.row];
    
    
    [cell.contentMoveView setTag:indexPath.row];
    
    cell.data = data;
    
    return cell;
    
}


-(void)cellOnClick:(UIButton*)sender{
    
    BorkerCellModel *data = [dataArray objectAtIndex:sender.tag];

    CommissionSubVc *vc = [[CommissionSubVc alloc]init];
    [vc queryDataByBrokerId:data.brokerId withBorkerName:data.brokerName];
      vc.hidesBottomBarWhenPushed = YES;;
    [self.navigationController pushViewController:vc animated:YES];
    
}





#pragma mark seachView delegate
-(NSArray*)getDataByKewWord:(NSString*)kewWord{
    
    return seachDataArray;
}


-(CGFloat)getCellHight{
    
    return 60;
}

-(NSInteger)getCellCount{
    
    return seachDataArray.count;
}

-(UITableViewCell*)getCellByTableView:(UITableView *)tableView WithIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *ID = @"BrokerCell";
    BrokerCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil)
    {
        cell = [[BrokerCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        
        [cell.contentMoveView addTarget:self action:@selector(searchViewCellOnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [cell initWithTableView:self.tableView];
        
        [cell beQueryStyleCell];

    }
    
    BorkerCellModel *data = [seachDataArray objectAtIndex:indexPath.row];
    
    [cell.contentMoveView setTag:indexPath.row];
    
    cell.data = data;
    
    return cell;
}



-(void)searchViewCellOnClick:(UIButton*)sender{

    BorkerCellModel *data = [seachDataArray objectAtIndex:sender.tag];
    CommissionSubVc *vc = [[CommissionSubVc alloc]init];
    [vc queryDataByBrokerId:data.brokerId withBorkerName:data.brokerName];
      vc.hidesBottomBarWhenPushed = YES;;
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)hideSearchView
{
    self.isSearchType = NO;
    self.seachDataArray = nil;
    self.keyword = @"";
    self.seachEt.text = @"";
    
    self.seachDataArray = nil;
    [self.cacelBtn setTitle:@"" forState:UIControlStateNormal];
    self.cacelBtn.enabled = NO;
}


#pragma mark textField的代理
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    NSMutableString *keyStr = [NSMutableString stringWithString:textField.text];
    
    if(![StringTool isBlankString:string])
    {
        [keyStr appendString:string];
    }else
    {
        NSUInteger length = keyStr.length - 1;
        
        NSRange rang =  NSMakeRange(0, length);
        
        keyStr =  [NSMutableString stringWithString:[keyStr substringWithRange:rang]];
    }
    
    self.keyword = keyStr;
    
    self.keyword = keyStr.length >0? keyStr:@"*";
    if([StringTool contentChinese:self.keyword]||self.keyword.length>=2)
    {
        self.isSearchType = YES;
        
        [self refreshData];
    }
    
    return true;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    if (dataArray.count == 0 ||dataArray == nil) {
        return;
    }
    
    [self.seachView show];
    
    [self.seachView tableViewReloadAndUpFrame];
    
}


- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
{
    if (dataArray.count == 0 ||dataArray == nil) {
        return YES;
    }
    
    [self.searchTv textDicChange:@""];
    
    [self.cacelBtn setTitle:@"取消" forState:UIControlStateNormal];
    self.cacelBtn.enabled = YES;
    
    self.isSearchType = YES;
    [self.seachView show];
    
    [self.seachView tableViewReloadAndUpFrame];
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView;
{
    [self.searchTv textDicChange:textView.text];
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimedString = [textView.text stringByTrimmingCharactersInSet:set];
    
    self.keyword = textView.text;
    if (trimedString.length == 0) {
        self.keyword = @"***********";
        
    }
    [self searchRefreshData];
    [self.seachView tableViewReloadAndUpFrame];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        [self.searchTv setText:@""];;
        [self.searchTv textDicChange:@""];
        [self.seachView hide];
        
        self.seachDataArray = nil;
        [self.cacelBtn setTitle:@"" forState:UIControlStateNormal];
        self.cacelBtn.enabled = NO;
        
    }
    self.keyword = @"***********";
    return YES;
}


- (IBAction)clickCancelBtn:(id)sender {
    
    self.keyword = @"********";
    [self.searchTv resignFirstResponder];
    [self.cacelBtn setTitle:@"" forState:UIControlStateNormal];
    self.cacelBtn.enabled = NO;
    [self.searchTv setText:@""];
    [self.searchTv textDicChange:@""];;
    [self.seachView hide];
    self.seachDataArray = nil;

}



@end
